package com.xiyoo.cw.service.impl;

import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiyoo.cw.common.Result;
import com.xiyoo.cw.common.constans.Constans;
import com.xiyoo.cw.common.enums.ResultCode;
import com.xiyoo.cw.config.TokenProvider;
import com.xiyoo.cw.domain.User;
import com.xiyoo.cw.domain.user.UserRequest;
import com.xiyoo.cw.mapper.UserMapper;
import com.xiyoo.cw.service.MailService;
import com.xiyoo.cw.service.UserService;
import com.xiyoo.cw.utils.CacheUtils;
import com.xiyoo.cw.utils.MailSenderUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @Description
 * @Author zhouzhongqing
 * @Date 2025/5/13 10:49
 * @Version 1.0
 **/
@Service
@Slf4j
public class UserServiceImpl implements UserService {

//    @Resource
//    private RedisUtil redisUtil;

    @Resource
    private CacheUtils cacheUtils;

    @Resource
    private UserMapper userMapper;

    @Resource
    private TokenProvider tokenProvider;

    @Override
    public Result<Object> getCaptcha(User user) {
        try {
            log.info("获取验证码开始，user={},nickName={}", user.getEmail(), user.getNickName());

            String captchaCode = generateCaptcha();
            String emailContent = String.format(Constans.EMAIL_CONTENT, captchaCode);
            log.info("获取验证码，user={},验证码={}", user.getEmail(), captchaCode);
            MailSenderUtil.sendMailTOSingleUser(user.getEmail(), Constans.EMAIL_TITLE, emailContent);

            cacheUtils.saveCode(user.getEmail(), captchaCode);
            log.info("获取验证码成功，user={},nickName={}", user.getEmail(), user.getNickName());
            return new Result<>(ResultCode.SUCCESS, captchaCode);
        } catch (Exception e) {
            log.error("获取验证码异常，user={},nickName={}", user.getEmail(), user.getNickName(), e);
            return new Result<>(ResultCode.SERVER_ERROR);
        }
    }


    @Override
//    @Transactional(rollbackFor = Exception.class)
    public Result<Object> login(UserRequest request) {
        // 获取缓存中的redis 验证码比对
        String email = request.getEmail();
//        String key = String.format(Constans.RedisKey.LOGIN, email);
//        String value = String.valueOf(redisUtil.get(key));
        if (!cacheUtils.validateCode(email, request.getCaptcha())) {
            log.info("登录验证码对比不正确，email={},验证码={}", email, request.getCaptcha());
            return new Result<>(ResultCode.CAPTCHA_ERROR);
        }
        log.info("登录验证码对比正确，email={},验证码={}", email, request.getCaptcha());

//        if (CharSequenceUtil.isNotBlank(value) && !CharSequenceUtil.equals(request.getCaptcha(), value)) {
//            log.info("登录验证码对比不正确，email={},key={},value={},验证码={}", email, key, value, request.getCaptcha());
//            return new Result<>(ResultCode.CAPTCHA_ERROR);
//        }

        User user = handleUserInfo(request);
        // 生成token
        String token = tokenProvider.generateToken(user);
        return new Result<>(ResultCode.SUCCESS, token);
    }

    private User handleUserInfo(UserRequest request) {
        String email = request.getEmail();
        // 如果有更新，没有新增
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, email);
        User selectOne = userMapper.selectOne(queryWrapper);
        if (Objects.isNull(selectOne) || CharSequenceUtil.isBlank(selectOne.getEmail())) {
            User user = User.builder().email(email).nickName(request.getNickName()).build();
            int rows = userMapper.insert(user);
            log.info("新增用户,email={},nickName={},row={}", email, request.getNickName(), rows);
            return user;
        } else {
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getEmail, email);
            User user = User.builder().nickName(request.getNickName()).build();
            int rows = userMapper.update(user, wrapper);
            log.info("更新用户昵称,email={},nickName={},row={}", email, request.getNickName(), rows);
            return selectOne;
        }

    }


    // 用于生成6位纯数字验证码
    public static String generateCaptcha() {
        // 使用ThreadLocalRandom提高性能
        StringBuilder captcha = new StringBuilder(6);
        for (int i = 0; i < 6; i++) {
            // 生成0-9的随机数字
            captcha.append(ThreadLocalRandom.current().nextInt(10));
        }
        return captcha.toString();
    }

    // 用于生成6位纯数字验证码
//    public static String generateCaptcha() {
//        Random random = new Random();
//        StringBuilder captcha = new StringBuilder();
//        for (int i = 0; i < 6; i++) {
//            captcha.append(random.nextInt(10)); // 生成0-9的随机数字
//        }
//        return captcha.toString();
//    }
}
